<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑标签' : '新建标签'"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
      <el-form-item label="标签名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入标签名称"
          maxlength="50"
          show-word-limit
          @blur="checkTagName"
        />
      </el-form-item>

      <el-form-item label="标签颜色" prop="color">
        <div class="color-input-container">
          <el-input
            v-model="form.color"
            placeholder="请选择或输入颜色"
            style="flex: 1"
            @input="handleColorInput"
          />
          <el-color-picker
            v-model="form.color"
            :predefine="predefineColors"
            @change="handleColorChange"
          />
          <div class="color-preview">
            <el-tag
              v-if="form.name && form.color"
              :color="form.color"
              :style="{ color: getTextColor(form.color) }"
              class="preview-tag"
            >
              {{ form.name }}
            </el-tag>
            <span v-else class="preview-placeholder">预览</span>
          </div>
        </div>
        <div class="color-tips">
          <span>支持十六进制颜色码（如：#FF5722）或使用颜色选择器</span>
        </div>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="isEdit && tag" label="使用统计">
        <div class="usage-stats">
          <div class="stat-item">
            <span class="label">使用次数:</span>
            <span class="value">{{ tag.useCount }}</span>
          </div>
          <div class="stat-item">
            <span class="label">使用频率:</span>
            <el-tag :type="getUsageLevelTagType(tag.usageLevel)" size="small">
              {{ TagManagementUtils.getUsageLevelText(tag.usageLevel) }}
            </el-tag>
          </div>
          <div v-if="tag.lastUsedTime" class="stat-item">
            <span class="label">最后使用:</span>
            <span class="value">{{ tag.lastUsedTime }}</span>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
        <el-button v-if="!isEdit" @click="handleGenerateColor">
          随机颜色
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  createTagApi,
  updateTagApi,
  checkTagNameApi,
  type TagInfo,
  type CreateTagRequest,
  type UpdateTagRequest,
  TagManagementUtils
} from "@/api/tag-management";

interface Props {
  visible: boolean;
  tag: TagInfo | null;
  isEdit: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  tag: null,
  isEdit: false
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  success: [];
}>();

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const submitting = ref(false);

// 预定义颜色
const predefineColors = [
  "#f56c6c",
  "#e6a23c",
  "#67c23a",
  "#1890ff",
  "#722ed1",
  "#eb2f96",
  "#fa541c",
  "#fadb14",
  "#52c41a",
  "#13c2c2",
  "#2f54eb",
  "#722ed1",
  "#fa8c16",
  "#a0d911",
  "#36cfc9"
];

// 表单数据
const form = reactive({
  name: "",
  color: "",
  status: 1
});

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: "请输入标签名称", trigger: "blur" },
    { min: 1, max: 50, message: "标签名称长度在1-50个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const validation = TagManagementUtils.validateTagName(value);
        if (!validation.valid) {
          callback(new Error(validation.message));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  color: [
    {
      validator: (rule, value, callback) => {
        const validation = TagManagementUtils.validateColor(value);
        if (!validation.valid) {
          callback(new Error(validation.message));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
};

// 监听对话框显示状态
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
    if (newVal) {
      initForm();
    }
  },
  { immediate: true }
);

watch(dialogVisible, newVal => {
  emit("update:visible", newVal);
});

// 计算属性
const getUsageLevelTagType = (level: number): string => {
  const typeMap: Record<number, string> = {
    0: "info",
    1: "success",
    2: "warning",
    3: "danger"
  };
  return typeMap[level] || "info";
};

// 初始化表单
const initForm = () => {
  if (props.isEdit && props.tag) {
    // 编辑模式
    Object.assign(form, {
      name: props.tag.name,
      color: props.tag.color || "",
      status: props.tag.status
    });
  } else {
    // 新建模式
    Object.assign(form, {
      name: "",
      color: TagManagementUtils.generateRandomColor(),
      status: 1
    });
  }

  // 清除验证状态
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 检查标签名称是否可用
const checkTagName = async () => {
  if (!form.name) return;

  try {
    const excludeId = props.isEdit && props.tag ? props.tag.id : undefined;
    const data = await checkTagNameApi(form.name, excludeId);
    console.log("标签名称检测结果:", data);

    if (data && data.code === 200) {
      const result = data.data;
      console.log("检测数据:", result);

      // 修复逻辑：后端返回 true 表示可用，false 表示已被使用
      if (result && result.available === false) {
        ElMessage.warning(result.message || "标签名称已存在，请使用其他名称");
      } else if (result && result.available === true) {
        console.log("标签名称可用");
      }
    }
  } catch (error) {
    console.error("检查标签名称失败:", error);
  }
};

// 处理颜色输入
const handleColorInput = (value: string) => {
  // 如果是 rgba 格式，转换为16进制
  if (value && value.startsWith("rgba")) {
    form.color = convertRgbaToHex(value);
  } else {
    form.color = value;
  }
  console.log("颜色输入变化:", { original: value, converted: form.color });
};

// 处理颜色选择器变化
const handleColorChange = (value: string) => {
  // 如果是 rgba 格式，转换为16进制
  if (value && value.startsWith("rgba")) {
    form.color = convertRgbaToHex(value);
  } else {
    form.color = value;
  }
  console.log("颜色选择器变化:", { original: value, converted: form.color });
};

// 将 rgba 颜色转换为16进制
const convertRgbaToHex = (rgba: string): string => {
  try {
    // 解析 rgba(r, g, b, a) 格式
    const match = rgba.match(
      /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/
    );
    if (!match) return rgba;

    const r = parseInt(match[1]);
    const g = parseInt(match[2]);
    const b = parseInt(match[3]);

    // 转换为16进制
    const toHex = (n: number) => {
      const hex = n.toString(16);
      return hex.length === 1 ? "0" + hex : hex;
    };

    const hexColor = `#${toHex(r)}${toHex(g)}${toHex(b)}`;
    console.log("RGBA转16进制:", { rgba, hex: hexColor });
    return hexColor;
  } catch (error) {
    console.error("颜色转换失败:", error);
    return rgba;
  }
};

// 生成随机颜色
const handleGenerateColor = () => {
  form.color = TagManagementUtils.generateRandomColor();
};

// 获取文字颜色
const getTextColor = (backgroundColor: string): string => {
  if (!backgroundColor) return "#000000";
  const hex = backgroundColor.replace("#", "");
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128 ? "#000000" : "#ffffff";
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    submitting.value = true;

    if (props.isEdit && props.tag) {
      // 更新标签
      const updateData: UpdateTagRequest = {
        id: props.tag.id,
        name: TagManagementUtils.cleanTagName(form.name),
        color: form.color || TagManagementUtils.generateColorByName(form.name),
        status: form.status
      };

      const data = await updateTagApi(updateData);

      if (data && data.code === 200) {
        ElMessage.success("标签更新成功");
        emit("success");
        handleCancel();
      } else {
        ElMessage.error(data?.message || "标签更新失败");
      }
    } else {
      // 创建标签
      const createData: CreateTagRequest = {
        name: TagManagementUtils.cleanTagName(form.name),
        color: form.color || TagManagementUtils.generateColorByName(form.name),
        status: form.status
      };

      const data = await createTagApi(createData);

      if (data && data.code === 200) {
        ElMessage.success("标签创建成功");
        emit("success");
        handleCancel();
      } else {
        ElMessage.error(data?.message || "标签创建失败");
      }
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败");
  } finally {
    submitting.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
.color-input-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.color-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
}

.preview-tag {
  font-weight: 500;
  border: none;
}

.preview-placeholder {
  font-size: 12px;
  color: #c0c4cc;
}

.color-tips {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.usage-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.stat-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.stat-item .label {
  min-width: 80px;
  font-weight: 500;
  color: #606266;
}

.stat-item .value {
  color: #303133;
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
